package com.zzptc.mzb.shucheng1130.Utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.Charset;

public class ProcessText {
    public  long pages;//总页数
    public final int SIZE=3000;//每一张的字节数
    public long bytescount;//字节总数
    public  long currentpage;//当前页面
    public RandomAccessFile readFile;

    public ProcessText(File file,long currentpage){
        try {
            readFile= new RandomAccessFile(file,"r");
            bytescount=readFile.length();//字节总数
            pages=bytescount/SIZE;//计算出文本的页数
            this.currentpage=currentpage;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //定位字节位置 根据页数定位文本的位置
private  void seek(long page){
    try {
        readFile.seek(page*SIZE);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

//在第2页就可以正常显示出内容 不影响阅读
private  String read(){
        //内容重叠防止 末尾字节乱码
        byte[]buffer=new  byte[SIZE+16];
    try {
        readFile.read(buffer);

    } catch (IOException e) {
        e.printStackTrace();
    }
    String str=new String(buffer, Charset.forName("utf-8"));
    str=str.replace("�","");
    return str;
}
public String getPre(){
        String content=null;
        if (currentpage<=1){
           seek(0);
           content=read();
           currentpage=1;
        }else {
            seek(currentpage-2);
            content=read();
            currentpage--;
        }
        return  content;
}
public  String getNext(){
        String content=null;
        if (currentpage>=pages){
            currentpage=pages;
            seek(currentpage);
            content=read();
        }else {
            seek(currentpage);
            content=read();
            currentpage++;
        }
        return content;
}

}
